package com.example.zwh.computershop.my_shopp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.zwh.computershop.Myapp;
import com.example.zwh.computershop.R;
import com.example.zwh.computershop.androidUtil.ActivityCollector;
import com.example.zwh.computershop.handleDataClient.handleData;
import com.example.zwh.computershop.sqlModel.User;

public class ModifyInfoActivity extends AppCompatActivity implements View.OnClickListener{

    private ImageView back_image;
    private EditText modify_name;
    private Button modify_name_save;
    private Myapp myapp;
    private Intent intent;

    private Toast toast;

    private int state; //接收服务器返回数据判断是否成功
    private String newName;//存取用户名用来作为修改用户名的中介
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_info);
        ActivityCollector.addActivity(this);
        initView();
        initEvent();
        initData();
    }

    void initView() {
        state = 0;
        myapp = (Myapp) getApplication();

        back_image = findViewById(R.id.back_image);
        modify_name = findViewById(R.id.modify_name);
        modify_name_save = findViewById(R.id.modify_name_save);
    }
    void initEvent() {
        back_image.setOnClickListener(this);
        modify_name_save.setOnClickListener(this);
    }
    void initData() {
        modify_name.setText(myapp.getUser().getUsername());
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.modify_name_save:
                newName = modify_name.getText().toString();
                modifySave();
                if (state == 2) {
                    toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                    finish();
                }else {
                    toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.back_image:
                finish();
                break;
        }
    }
    //保存修改后的信息
    //修改用户名
    public void modifySave() {
        Thread t = new Thread(new SaveThread());
        t.start();
        //等待线程返回
        try {
            t.join();
        }catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }

    //保存修改线程
    class SaveThread extends Thread {
        @Override
        public void run() {
            User userTemp = new User();
            userTemp.setUser(myapp.getUser());
            userTemp.setUsername(newName);
            state = handleData.handleInfo(userTemp);
            if (state == 2) {
                myapp.getUser().setUser(userTemp);
            }
        }
    }
}
